package com.ninetaildemonfox.zdl.socialproject.mvp.ui.main;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.easeui.utils.map.JSONUtils;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.kongzue.dialog.v3.WaitDialog;
import com.ninetaildemonfox.zdl.ninetaildemonfox.base.BaseFragment;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.contract.RadioStationContract;
import com.ninetaildemonfox.zdl.socialproject.mvp.presenter.RadioStationPresenter;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.AuthenticationCenterActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.CityListSelectActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.DetailInterfaceActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.MainActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity.VipActivity;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.adapter.RadioStationAdapter;
import com.ninetaildemonfox.zdl.socialproject.utils.ToastUtil;
import com.ninetaildemonfox.zdl.socialproject.utils.dialog.ReleaseDialog;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * @author NineTailDemonFox
 * @date 2019/7/15 15:11
 * 功能描述： 电台界面
 * 联系方式：1037438704@qq.com
 */
public class RadioStationFragment extends BaseFragment implements RadioStationContract {
    @BindView(R.id.image_left_finish)
    ImageView imageleftFinish;
    @BindView(R.id.text_release)
    TextView textRelease;
    @BindView(R.id.text_city)
    TextView textCty;
    @BindView(R.id.text_center)
    TextView textCenter;
    @BindView(R.id.text_right)
    TextView textRight;
    @BindView(R.id.text_date)
    TextView textDate;
    @BindView(R.id.text_time)
    TextView textTime;
    @BindView(R.id.recycerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    private RadioStationAdapter radioStationAdapter;
    @BindView(R.id.text_gone_view)
    LinearLayout textGoneView;
    private int thisCont = 1;
    private Drawable drawable;
    private RadioStationPresenter presenter;
    private int page = 1;
    private static String type = "";
    private String cityId;

    public static RadioStationFragment newInstance() {
        return new RadioStationFragment();
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_radio_station;
    }

    @Override
    protected void onInitView(Bundle savedInstanceState) {
        initView();
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void initData() {
        textCenter.setText("电台");
        textRight.setVisibility(View.VISIBLE);
        textRight.setText("发布");
        //刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                http();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                http();
            }
        });
        //点赞点击事件
        radioStationAdapter.setmOnClick(new RadioStationAdapter.ItemOnClick() {
            @Override
            public void onClick(int position, Map<String, String> data, int type) {
                switch (type) {
                    case 1:
                        //点赞
                        presenter.addOrderGood(token, data.get("id"), position);
                        break;
                    case 2:
                        //结束报名
                        MessageDialog.show(fgtContext, "是否结束报名！", "", "确认", "取消")
                                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                                    @Override
                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                        presenter.endOrder(token, data.get("id"), position);
                                        return false;
                                    }
                                });
                        break;
                    case 3:
                        if (getSex.equals(data.get("sex"))) {
                            ToastUtil.show("不能查看同性别的人");
                            return;
                        }
                        panduan(data);
                        break;
                    default:
                }
            }
        });
    }

    private void http() {
        presenter.getOrderList(token, page + "", type, cityId);
    }

    private void initView() {
        presenter = new RadioStationPresenter(this, fgtContext);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        radioStationAdapter = new RadioStationAdapter(getContext());
        radioStationAdapter.adpType(2);
        radioStationAdapter.setNoMore(R.layout.view_nomore);
        recyclerView.setAdapter(radioStationAdapter);
        page = 1;
        WaitDialog.show(fgtContext, "数据加载中...");
        http();

    }

    @OnClick({R.id.text_right, R.id.text_time, R.id.text_gone_view, R.id.text_release, R.id.text_date, R.id.text_city})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_right:
                thisCont = 1;
                textGoneView.setVisibility(View.GONE);
                startActivity(new Intent(getContext(), ReleaseDialog.class));
                break;
            case R.id.text_time:
                if (thisCont == 1) {
                    drawable = mContext.getResources().getDrawable(R.mipmap.ic_drop_down_true);
                    thisCont = 2;
                    textGoneView.setVisibility(View.VISIBLE);
                } else {
                    drawable = mContext.getResources().getDrawable(R.mipmap.ic_drop_down);
                    thisCont = 1;
                    textGoneView.setVisibility(View.GONE);
                }
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textTime.setCompoundDrawables(null, null, drawable, null);

                break;
            case R.id.text_gone_view:
                drawable = mContext.getResources().getDrawable(R.mipmap.ic_drop_down);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textTime.setCompoundDrawables(null, null, drawable, null);
                thisCont = 1;
                textGoneView.setVisibility(View.GONE);
                break;
            case R.id.text_release:
                type = "1";
                drawable = mContext.getResources().getDrawable(R.mipmap.ic_drop_down);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textTime.setCompoundDrawables(null, null, drawable, null);
                thisCont = 1;
                textGoneView.setVisibility(View.GONE);
                textTime.setText("发布时间");
                WaitDialog.show(fgtContext, "数据加载中...");
                http();
                break;
            case R.id.text_date:
                type = "2";
                drawable = mContext.getResources().getDrawable(R.mipmap.ic_drop_down);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                textTime.setCompoundDrawables(null, null, drawable, null);
                thisCont = 1;
                textGoneView.setVisibility(View.GONE);
                textTime.setText("约会时间");
                WaitDialog.show(fgtContext, "数据加载中...");
                http();
                break;
            case R.id.text_city:
                startActivityForResult(new Intent(getContext(), CityListSelectActivity.class), 1);
                break;
            default:
        }
    }

    @Override
    public void RadioSuccess(List<Map<String, String>> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (page == 1) {
            radioStationAdapter.clear();
            radioStationAdapter.addAll(data);
        } else {
            if (data == null) {
                ToastUtil.show("没有更多数据了");
                return;
            }
            radioStationAdapter.addAll(data);
        }
    }

    @Override
    public void RadioFailed(String msg) {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void addOrderGood(int item, int count) {
        List<Map<String, String>> allData = radioStationAdapter.getAllData();
        if (count == 2) {
            radioStationAdapter.remove(item);
//            allData.remove(item);
//            radioStationAdapter.clear();
//            radioStationAdapter.addAll(allData);
        } else {
            String good_count = allData.get(item).get("good_count");
            allData.get(item).put("good", "2");
            allData.get(item).put("good_count", (Integer.valueOf(good_count) + 1) + "");
            radioStationAdapter.notifyItemChanged(item);
        }

    }

    @Override
    public void addEnlist(int item) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            cityId = bundle.getString("city");
            textCty.setText(cityId);
            page = 1;
            http();
        }
    }

    //更新报名条目
    public void itemCount(int item) {
        // 是否报名  1是 2否
//        data.get("baoming")
//        报名人数
//        data.get("baoming_count")
        List<Map<String, String>> allData = radioStationAdapter.getAllData();
        String baoming_count = allData.get(item).get("baoming_count");
        allData.get(item).put("baoming_count", (Integer.valueOf(baoming_count) + 1) + "");
        allData.get(item).put("baoming", "1");
        radioStationAdapter.notifyItemChanged(item);
    }

    private void panduan(Map<String, String> thisdata) {
        //                             是否vip 1否 2是           1未认证 2 已认证
        if (getSex.equals("1")) {
            if (getVip.equals("1")) {
                HttpRequest.POST(fgtContext, "Index/seeCount"
                        , new Parameter()
                                .add("token", token)
                                .add("cover_member_id", thisdata.get("member_id"))
                        , new ResponseListener() {
                            @Override
                            public void onResponse(String response, Exception error) {
                                if (error != null) {
                                    ToastUtil.show("网络异常");
                                    return;
                                }
                                Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                if (map.get("code").equals("-1")) {
                                    BaseActivity.alerDialog.show();
                                } else if (map.get("code").equals("1")) {
                                    Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                                    if (data.get("look").equals("1")) {
                                        DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                                        return;
                                    }
                                    int count = Integer.valueOf(data.get("count"));
                                    if (count <= 3 && count > 0) {
                                        //立即开通
                                        MessageDialog.show(fgtContext, "剩余机会" + data.get("count"), "非会员每天只能查看" + data.get("total") + "位女士", "升级会员", "继续查看")
                                                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        VipActivity.start(me, "1", 1);
                                                        return false;
                                                    }
                                                })
                                                .setOnCancelButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                                                        return false;
                                                    }
                                                })
                                        ;
                                    } else if (count == 0) {
                                        ToastUtil.show("您没有次数了");
                                    } else {
                                        DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                                    }
                                } else if (map.get("code").equals("0")) {
                                    ToastUtil.show(map.get("message"));
                                }
                            }
                        });
            } else {
                //会员
                DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                return;
            }
        } else {
            if (getIdentification.equals("1")) {
                HttpRequest.POST(fgtContext, "Index/seeCount"
                        , new Parameter()
                                .add("token", token)
                                .add("cover_member_id", thisdata.get("member_id"))
                        , new ResponseListener() {
                            @Override
                            public void onResponse(String response, Exception error) {
                                if (error != null) {
                                    return;
                                }
                                Map<String, String> map = JSONUtils.parseKeyAndValueToMap(response);
                                if (map.get("code").equals("-1")) {
                                    BaseActivity.alerDialog.show();
                                } else if (map.get("code").equals("1")) {
                                    Map<String, String> data = JSONUtils.parseKeyAndValueToMap(map.get("data"));
                                    int count = Integer.valueOf(data.get("count"));
                                    if (data.get("look").equals("1")) {
                                        DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                                        return;
                                    }
                                    if (count <= 3 && count > 0) {
                                        //立即开通
                                        MessageDialog.show(fgtContext, "剩余机会" + data.get("count"), "未认证每天只能查看" + data.get("total") + "位男士", "去认证", "继续查看")
                                                .setOnOkButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        //去认证
                                                        Intent intent = new Intent(fgtContext, AuthenticationCenterActivity.class);
                                                        Bundle bundle = new Bundle();
                                                        bundle.putInt("dataSize", 1);
                                                        intent.putExtras(bundle);
                                                        startActivity(intent);
                                                        return false;
                                                    }
                                                })
                                                .setOnCancelButtonClickListener(new OnDialogButtonClickListener() {
                                                    @Override
                                                    public boolean onClick(BaseDialog baseDialog, View v) {
                                                        DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                                                        return false;
                                                    }
                                                })
                                        ;
                                    } else if (count == 0) {
                                        ToastUtil.show("您没有次数了请先认证");
                                        return;
                                    } else {
                                        DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
                                    }

                                } else if (map.get("code").equals("0")) {
                                    ToastUtil.show(map.get("message"));
                                }
                            }
                        });
            } else {
                DetailInterfaceActivity.start(getContext(), thisdata.get("member_id"), "1");
            }
        }
    }
}
